<?php

class FFapiClient
{
	/**
	 * print the debug info
	 *
	 * @ignore
	 */
	public $debug = FALSE;
	
	public $error = NULL;
		
	/**
	 * @ignore
	 */
	public $access_token;

	private $unCheckDo = array("registerUser",	"resetPasswd", "userLogin", "openUidLogin", "getExchangelist");
	
	function __construct( $token =NULL ) {
		$this->access_token = $token;
	}
    
    function apiBaseURL() {
		global $_SC;
    	return $_SC ['apiurl']."snsApi.php?do="; 
    }
    
	/**
	 * access_token 接口
	 * userLogin 
	 */
	function getAccessToken($username, $password) {
	    global $_SC;
		$url = $_SC['domain']."snsApi.php?do=userLogin"; 
		$param = array(
				"account"=>$username,
				"passwd"=>$password,
				"registerDevice"=>'FFWEB-1.0',
				"deviceSN"=>'FFWEB-F0C8CB2A30425FCB45EC50EAEF',
		);

		$result = $this->getHttpResponsePOST($url, $this->buildRequestPara("userLogin", json_encode($param)));
		$result = $this->parseData($result);
		return $result;
	}
	
	
	function getDiaryInfoWithCommentReply($oUid, $bodyId,  $uid) {
		// {"bodyId":101127023,"uid":3731418}
		$url =  $this->apiBaseURL() . "getDiaryInfoWithCommentReply";
		$param = array();
		$param['uid'] = $oUid;
		$param['bodyId'] = $bodyId;
		$param['start'] = 0;
		$param['length'] =20;
		
// 		var_dump($param);exit;
		$data = $this->buildRequestPara("getDiaryInfoWithCommentReply", json_encode($param), $uid);
		$json = $this->getHttpResponsePOST($url, $this->buildRequestPara("getDiaryInfoWithCommentReply", json_encode($param), $uid));
		$result = $this->parseData($json);
		//echo '<pre>';var_dump($result['resultData']);exit;
		return $result['resultData'];
	}

	function postManage($action, $param, $uid) {
		$url =  $this->apiBaseURL() . "postManage";
		$param['action'] = $action;
		$data = $this->buildRequestPara("postManage", json_encode($param), $uid);
		$json = $this->getHttpResponsePOST($url, $data);
		//echo $json;
		$result = $this->parseData($json);
		return $result['resultData'];
	}
	
	function buildRequestPara($apiName, $strJsonParam, $hostId = 0) {
		$timestamp = time();
		if($hostId > 0){
			$tempStr = $apiName .$hostId. $strJsonParam .$timestamp.($this->getSelfToken($apiName));
		}else{
			$tempStr = $apiName .$strJsonParam .$timestamp.($this->getSelfToken($apiName));
		}
		$arr = array(
				"time"=>$timestamp,
				"signature"=>md5($tempStr),
				"param"=>$strJsonParam
		);

		if($hostId > 0){
			$arr['hostUid'] = $hostId;
		}

		return  $arr;
	}
	
	function getSelfToken($apiName) {
		$mustToken = true;
		$cryptToken = "";
		if(in_array($apiName, $this->unCheckDo)){
			$mustToken = false;
		}
		
		if ($mustToken) {
			if ($this->access_token == "" || strlen($this->access_token) != 32) {
				$cryptToken = "";
			} else {
				$cryptToken = $this->cryptToken($this->access_token);
			}
		}else{
			$cryptToken = "ffrj@SNS";
		}
		return $cryptToken;
	}
	
    private function cryptToken($token) {
        #   if (empty($token))  return  'ffrj@SNS';
        $length =   strlen($token);
        if (32  !=  $length)
        {
            return  $token;
        }
        $cryptString=   substr($token, 2, 3);
        $cryptNum   =   hexdec($cryptString);
        $cryptBase  =   $cryptNum % 8;

        $cryptArray =   array(
                            0   =>  array( 0,  1,  3,  7, 15, 31),
                            1   =>  array( 7, 15, 31,  0,  1,  3),
                            2   =>  array( 4,  5,  7, 11, 19,  3),
                            3   =>  array(19,  3,  4,  5,  7, 11),
                            4   =>  array(18, 19, 21, 25,  1, 17),
                            5   =>  array(25,  1, 17, 18, 19, 21),
                            6   =>  array(27, 28, 30,  2, 10, 26),
                            7   =>  array( 2, 10, 26, 27, 28, 30),
                        );

        $tmpToken   =   NULL;
        foreach ($cryptArray[$cryptBase]  as  $id)
        {
            $tmpToken   .=  $token[$id];
        }
        return  $tmpToken;
    }
    
    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $para 请求的数据
     * @param $input_charset 编码格式。默认值：空值
     * return 远程输出的数据
     */
    function getHttpResponsePOST($url, $para, $input_charset = '') {
    	$this->errorNo =NULL;
    	$curl = curl_init($url);
    	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    	curl_setopt($curl,CURLOPT_POST,true); // post传输数据
    	curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
    	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
		curl_setopt($curl, CURLOPT_USERAGENT, "FFWEB_1.0-API");
    	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_ENCODING, "");
		curl_setopt($curl, CURLOPT_HEADER, FALSE);
    	$responseText = curl_exec($curl);

//    	 var_dump( curl_error($curl) );exit;//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    	curl_close($curl);
    	return $responseText;
    }
    
    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * return 远程输出的数据
     */
    function getHttpResponseGET($url) {
    	$this->errorNo =NULL;
    	$curl = curl_init($url);
    	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
		curl_setopt($curl, CURLOPT_USERAGENT, "FFWEB_1.0-API");
    	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_ENCODING, "");
		curl_setopt($curl, CURLOPT_HEADER, FALSE);
    	$responseText = curl_exec($curl);
    	//var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    	curl_close($curl);
    
    	return $responseText;
    }
    
    function parseData($result){
    	$data = json_decode($result, true);
    	if($data['errorNo']){
    		$this->error = $data['errorNo'];
    	}
    	return $data;
    }
    
    // 对象转换成数组
    function object_to_array($obj) {
    	$_arr = is_object ( $obj ) ? get_object_vars ( $obj ) : $obj;
    	foreach ( $_arr as $key => $val ) {
    		$val = (is_array ( $val ) || is_object ( $val )) ? $this->object_to_array ( $val ) : $val;
    		$arr [$key] = $val;
    	}
    	return $arr;
    }
}


?>